<template>
  <div>
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" label-width="68px" size="mini">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="姓名" prop="staffName">
            <el-input v-model="queryParams.staffName" clearable placeholder="请输入" @keyup.enter.native="handleQuery"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="职别" prop="staffLevels">
            <el-select v-model="queryParams.staffLevels" clearable placeholder="请选择">
              <el-option v-for="item in categoryOptions" :key="item.jobCategoryId" :label="item.jobName"
                         :value="item.jobCategoryId"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="入职时间">
            <el-date-picker v-model="dateRange" end-placeholder="结束日期" range-separator="-" start-placeholder="开始日期"
                            type="daterange" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="手机号码" prop="staffPhone">
            <el-input v-model="queryParams.staffPhone" clearable placeholder="请输入" @keyup.enter.native="handleQuery"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="10px">
            <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['cld:staff:add']" icon="el-icon-plus" plain size="mini" type="primary"
                   @click="handleAdd">新增人员
        </el-button>
        </el-col>
        <el-col :span="1.5">
        <el-button v-hasPermi="['cld:staff:import']" icon="el-icon-upload2" plain size="mini" type="primary"
                   @click="handleImport">批量导入
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button v-hasPermi="['cld:staff:export']" icon="el-icon-download" plain size="mini" type="primary"
                   @click="handleExport">列表导出
        </el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="staffList" border>
      <el-table-column align="center" label="员工编号" prop="staffId" width="80px;"/>
      <el-table-column align="center" label="员工姓名" prop="staffName" width="100px;"/>
      <el-table-column align="center" label="性别" prop="staffSex" width="80px;">
        <template slot-scope="scope">
          {{ formatGender(scope.row.staffSex) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="年龄" width="80px;">
        <template slot-scope="scope">
          {{ calculateAge(scope.row.staffIdcard) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="身份证号" prop="staffIdcard" width="200px;"/>
      <el-table-column align="center" label="联系方式" prop="staffPhone" width="150px;"/>
      <el-table-column align="center" label="职务" prop="jobName" width="100px;"/>
      <el-table-column align="center" label="银行卡号" prop="bankCard" width="200px;">
        <template slot-scope="scope">
          {{ scope.row.bankCard ? scope.row.bankCard.replace(/\s/g, '').replace(/[^\d]/g, '').replace(/(\d{4})(?=\d)/g, '$1 ') : '' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="紧急联系人" prop="urgentLinkman" width="150px;"/>
      <el-table-column align="center" label="紧急联系人电话" prop="urgentLinkmanPhone" width="150px;"/>
      <el-table-column align="center" label="家庭住址" prop="staffAddress"/>
      <el-table-column align="center" label="推荐人" prop="recommenStaffId" width="150px;"/>
      <el-table-column align="center" label="入职时间" prop="employmentTime" width="100px;">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.employmentTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="150px;">
        <template slot-scope="scope">
          <el-button v-hasPermi="['cld:staff:jobs']" size="mini" type="text"
                     @click="handleAllotJobs(scope.row)">分配岗位
          </el-button>
          <el-dropdown v-hasPermi="['cld:staff:edit', 'cld:staff:invalid', 'cld:staff:remove', 'cld:staff:resume']" size="mini"
                       @command="(command) => handleCommand(command, scope.row)">
            <el-button icon="el-icon-d-arrow-right" size="mini" type="text">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-hasPermi="['cld:staff:resign']" command="handleResignation"
              >离职
              </el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cld:staff:edit']" command="handleResetPassword"
                                >重置密码
              </el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cld:staff:resume']" command="handleResume"
                                >履历表
              </el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cld:staff:edit']" command="handleUpdate"
                               >修改
              </el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cld:staff:invalid']" command="handleInvalid"
                               >设为黑名单
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total"
                @pagination="getList"/>

    <!-- 修改人员 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="open" append-to-body title="个人信息录入"
               width="50%">
      <add-staff-vue v-if="open" ref="addStaff" :staffId="staffId" @success="handleSubmitSuccess"></add-staff-vue>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitStaff">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配岗位 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="jobOpen" append-to-body title="分配岗位"
               width="50%">
      <el-form ref="jobForm" :model="jobForm" label-width="100px" size="mini">
        <el-row :gutter="20">
          <el-form-item :rules="{
            required: true, message: '项目岗位不能为空', trigger: 'blur'
          }" label="选择岗位" prop="jobsId">
            <el-cascader-panel v-model="jobForm.jobsId" :options="projectJobOptions"></el-cascader-panel>
          </el-form-item>
        </el-row>
        <el-row :gutter="20">
          <el-form-item :rules="{
            required: true, message: '合同附件不能为空', trigger: 'blur'
          }" label="合同附件" prop="attachment">
            <file-upload v-model="jobForm.attachment" @input="handleFileInput"
            :fileType="['doc', 'docx', 'pdf','png', 'jpg', 'jpeg']"
            />
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAllotJobs">确 定</el-button>
        <el-button @click="jobOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 履历表查看 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="resumeOpen" append-to-body title="履历表"
    width="900px">
      <div id="printLLBForm">
        <staff-resume-view :staffId="staffId"> </staff-resume-view>
      </div>
     <div slot="footer" class="dialog-footer">
        <el-button v-print="'#printLLBForm'" type="primary"
          >打印</el-button
        >
        <el-button @click="resumeOpen = false">关 闭</el-button>
    </div>
    </el-dialog>

    <!-- 离职 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="resigOpen" append-to-body title="离职"
               width="500px">
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <el-row :gutter="20">
          <el-form-item :rules="{
            required: true, message: '离职原因不能为空', trigger: 'blur'
          }" label="离职原因" prop="resignReason">
            <el-input v-model="form.resignReason" :rows="4" placeholder="请输入" type="textarea"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="20">
          <el-form-item :rules="{
            required: true, message: '离职时间不能为空', trigger: 'blur'
          }" label="离职时间" prop="resignTime">
            <el-date-picker v-model="form.resignTime" value-format="yyyy-MM-dd" placeholder="选择日期" style="width: 100%;"
                            type="date"></el-date-picker>
          </el-form-item>
        </el-row>
        <el-row :gutter="20">
          <el-form-item :rules="{
            required: true, message: '离职申请表不能为空', trigger: 'blur'
          }" label="离职申请表" prop="resignTableImg">
            <file-upload v-model="form.resignTableImg" @input="handleFileInput"/>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitResignation">确 定</el-button>
        <el-button @click="resigOpen = false">取 消</el-button>
      </div>
    </el-dialog>


     <!-- 员工导入对话框 -->
     <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport + '&supplierId=' + queryParams.supplierId" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的员工数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {delStaff, listStaff, updateStaff,resetPasswordStaff,getStaff,resignStaff} from "@/api/cld/staff";
import addStaffVue from "./addStaff.vue";
import {getListCategory} from '@/api/cld/category'
import {selectedProjectJob} from '@/api/cld/publicCommon'
import {addStaffContract} from '@/api/cld/staffContract'
import { getToken } from "@/utils/auth";
import staffResumeView from './staffResumeView.vue';
export default {
  name: "Staff",
  dicts: ['cld_staff_levels'],
  inject: ['formatGender'],
  components: {
    addStaffVue,
    staffResumeView
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 人员花名册表格数据
      staffList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      resumeOpen: false,
      resumeImg: '',
      // 分配岗位弹框
      jobOpen: false,
      jobForm: {},
      // 岗位列表
      projectJobOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        staffName: null,
        staffStatus: 1,
        isPrepared: 0,
        staffPhone: null
      },
      // 职别列表
      categoryOptions: [],
      dateRange: [],
      // 员工导入参数
      upload: {
        // 是否显示弹出层（员工导入）
        open: false,
        // 弹出层标题（员工导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的商品数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/cld/staff/importData"
      },
      form:{},
      resigOpen: false,
      staffId: null
    };
  },
  created() {
    this.getList();
    // 获取职别列表
    this.handleGetListCategory();

  },
  methods: {
    /** 查询人员花名册列表 */
    getList() {
      this.loading = true;
      listStaff(this.addDateRange(this.queryParams, this.dateRange, 'EmploymentTime')).then(response => {
        this.staffList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 职别列表
    handleGetListCategory() {
      getListCategory().then(res => {
        this.categoryOptions = res.data;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 提交
    submitStaff() {
      this.$refs.addStaff.submitForm();
    },
    // 提交回调
    handleSubmitSuccess() {
      this.open = false;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResignation":
          this.handleResignation(row);
          break;
        case "handleUpdate":
          this.handleUpdate(row);
          break;
        case "handleInvalid":
          this.handleInvalid(row);
          break;
        case "handleDelete":
          this.handleDelete(row);
          break;
        case "handleResume":
          this.handleResume(row);
          break;
        case "handleResetPassword":
          this.handleResetPassword(row);
          break;
        default:
          break;
      }
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    // 修改员工
    handleUpdate(row) {
      this.staffId = row.staffId;
      this.open = true;
    },
    // 分配岗位
    handleAllotJobs(row) {
      this.jobForm = {
        staffId: row.staffId
      };
      selectedProjectJob(3).then(res => {
        this.projectJobOptions = res.data;
        this.jobOpen = true;
      })
    },
    // 分配岗位确认
    submitAllotJobs() {
      this.$refs["jobForm"].validate(valid => {
        if (valid) {
          // 取出项目Id 岗位id
          this.jobForm.projectId = this.jobForm.jobsId[1];
          this.jobForm.jobId = this.jobForm.jobsId[3];
          addStaffContract(this.jobForm).then(res => {
            this.jobOpen = false;
            this.$modal.msgSuccess("操作成功");
            this.getList();
          })
        }
      })
    },
    // 无效
    handleInvalid(row) {
      this.$prompt('', '拉黑原因', {
        center: true,
        inputType: 'textarea',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        row.staffStatus = 4;
        row.blackReason = value;
        updateStaff(row).then(response => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        });
      })
    },
    // 离职
    handleResignation(row) {
      this.reset();
      getStaff(row.staffId).then(res => {
        this.form = res.data;
        this.resigOpen = true;
      })
    },
    // 离职提交
    submitResignation() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          resignStaff(this.form).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.resigOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除员工姓名为"' + row.staffName + '"的数据项？').then(function () {
        return delStaff(row.staffId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 附件回调
    handleFileInput(e) {
      this.jobForm.attachment = e;
    },
    // 履历表查看
    handleResume(row){
      this.resumeOpen = true;
      this.staffId = row.staffId;
    },
     /** 导入按钮操作 */
     handleImport() {
      this.upload.title = "员工导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('cld/staff/importTemplate', {
      }, `员工导入_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
     // 重置密码
     handleResetPassword(row) {
      this.$modal.confirm('是否重置密码为[123456]？').then(function () {
        return resetPasswordStaff(row.staffId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => { });
    },
  }
};
</script>
<style scoped>
.el-range-editor.el-input__inner {
  width: 100%;
}

.el-select {
  width: 100%;
}

.el-image{
  width: 100%;
}

</style>
